//
//  HRDynamicSoundAndImageBackGroundView.m
//  Hear
//
//  Created by mac on 2017/7/26.
//  Copyright © 2017年 mac. All rights reserved.
//

#import "HRDynamicSoundAndImageBackGroundView.h"
#import "YYControl.h"
#import "YYPhotoGroupView.h"
#import "DOUAudioStreamer.h"
#import "Track.h"

static void *kStatusKVOKey = &kStatusKVOKey;
static void *kDurationKVOKey = &kDurationKVOKey;
static void *kBufferingRatioKVOKey = &kBufferingRatioKVOKey;
@interface HRDynamicSoundAndImageBackGroundView ()
@property (nonatomic,strong)YYControl *showImageView;
@property(nonatomic, strong)UIImageView *leftImageView;
@property(nonatomic, strong)UIImageView *rightImageView;
@property(nonatomic, strong)UILabel *timeLabel;
@property(nonatomic, strong)UIImageView *voicImageView;
@property(nonatomic, strong)DOUAudioStreamer *streamer;

@end
@implementation HRDynamicSoundAndImageBackGroundView

-(void)setDynamicModel:(HRDynamicModel *)dynamicModel{
    _dynamicModel = dynamicModel;
    
    CGFloat leftPading = 15;

    self.leftImageView.hidden = NO;
    self.rightImageView.hidden = NO;
    self.voicImageView.hidden = NO;
    
    
    UIView *imageView = self.showImageView;
    imageView.hidden = NO;
    imageView.frame = CGRectMake(leftPading, 0, (kFullWidth-leftPading*2)/2, 120);
    
    self.leftImageView.frame = CGRectMake(imageView.right-70, imageView.bottom-30, 70, 30);
    
    self.rightImageView.frame = CGRectMake(self.leftImageView.right, self.leftImageView.top-3, 31, 35);

    self.timeLabel.frame = CGRectMake(self.leftImageView.left, imageView.bottom-30, self.leftImageView.width, 30);
    
    self.voicImageView.frame = CGRectMake(self.rightImageView.left, self.rightImageView.top+15, 30, 30);
    self.voicImageView.centerY = self.timeLabel.centerY;

    self.timeLabel.text = [NSString stringWithFormat:@"%@S",dynamicModel.soundAndImageConentModel.SoundLength];
    
    
    if (dynamicModel.isPlaying){
        [self.voicImageView startAnimating];
        
    }else{
        [self.voicImageView stopAnimating];
    }
    
    
    [imageView.layer removeAnimationForKey:@"contents"];

    @weakify(imageView);

    [imageView.layer setImageWithURL:dynamicModel.soundAndImageConentModel.pics[0]  placeholder:[UIImage imageNamed:@"默认加载图"]
                             options:YYWebImageOptionAvoidSetImage
                          completion:^(UIImage *image, NSURL *url, YYWebImageFromType from, YYWebImageStage stage, NSError *error){                             @strongify(imageView);
                              if (!imageView) return;
                              if (image && stage == YYWebImageStageFinished) {
                                  int width = image.size.width;
                                  int height = image.size.height;
                                  CGFloat scale = (height / width) / (imageView.height / imageView.width);
                                  if (scale < 0.99 || isnan(scale)) { // 宽图把左右两边裁掉
                                      imageView.contentMode = UIViewContentModeScaleAspectFill;
                                      imageView.layer.contentsRect = CGRectMake(0, 0, 1, 1);
                                  } else { // 高图只保留顶部
                                      imageView.contentMode = UIViewContentModeScaleAspectFill;
                                      imageView.layer.contentsRect = CGRectMake(0, 0, 1, (float)width / height);
                                  }
                                  ((YYControl *)imageView).image = image;
                                  if (from != YYWebImageFromMemoryCacheFast) {
                                      CATransition *transition = [CATransition animation];
                                      transition.duration = 0.15;
                                      transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut];
                                      transition.type = kCATransitionFade;
                                      [imageView.layer addAnimation:transition forKey:@"contents"];
                                  }
                              }
                          }];
}


-(instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self){
        
        
        YYControl *imageView = [YYControl new];
        imageView.userInteractionEnabled = YES;
        imageView.hidden = YES;
        imageView.clipsToBounds = YES;
        imageView.backgroundColor = CustomColor(244, 244, 244, 1);
        imageView.exclusiveTouch = YES;
        
        WeakSelf
        UITapGestureRecognizer *imageTap = [[UITapGestureRecognizer alloc] initWithActionBlock:^(id  _Nonnull sender) {
            [weakSelf clickImageAtIndex:0];
        }];
        [imageView addGestureRecognizer:imageTap];
        [self addSubview:imageView];
        
        self.showImageView = imageView;
        
        
        self.leftImageView = [UIImageView new];
        self.leftImageView.image = [UIImage imageNamed:@"圆角矩形"];
        self.leftImageView.contentMode = UIViewContentModeScaleAspectFill;
        self.leftImageView.clipsToBounds = YES;
        [self addSubview:self.leftImageView];
        self.leftImageView.userInteractionEnabled = YES;
        
        UITapGestureRecognizer *leftImageTap = [[UITapGestureRecognizer alloc] initWithActionBlock:^(id  _Nonnull sender) {
            [weakSelf playSound];
        }];
        [self.leftImageView addGestureRecognizer:leftImageTap];
        
        self.rightImageView = [UIImageView new];
        self.rightImageView.image = [UIImage imageNamed:@"半圆"];
        self.rightImageView.contentMode = UIViewContentModeScaleAspectFill;
        self.rightImageView.clipsToBounds = YES;
        [self addSubview:self.rightImageView];
        
        UITapGestureRecognizer *rightImageTap = [[UITapGestureRecognizer alloc] initWithActionBlock:^(id  _Nonnull sender) {
            [weakSelf playSound];
        }];
        [self.rightImageView addGestureRecognizer:rightImageTap];
        
        
        self.timeLabel = [UILabel new];
        self.timeLabel.font = CustomUIFont(13);
        self.timeLabel.textColor =[UIColor whiteColor];
        [self addSubview:self.timeLabel];
        self.timeLabel.textAlignment = 1;
        
        
        
        
        self.voicImageView = [UIImageView new];
        self.voicImageView.image = [UIImage imageNamed:@"语音图片_语音气泡5"];
        //        self.rightImageView.contentMode = UIViewContentModeScaleAspectFill;
        self.voicImageView.clipsToBounds = YES;
        [self addSubview:self.voicImageView];
        self.voicImageView.userInteractionEnabled = YES;
        
        UITapGestureRecognizer *voiceImageTap = [[UITapGestureRecognizer alloc] initWithActionBlock:^(id  _Nonnull sender) {
            [weakSelf playSound];
        }];
        [self.voicImageView addGestureRecognizer:voiceImageTap];
        
        NSArray * animateNames = @[@"语音图片_语音气泡1",@"语音图片_语音气泡2",@"语音图片_语音气泡3",@"语音图片_语音气泡4",@"语音图片_语音气泡5"];
        
        NSMutableArray * animationImages = [[NSMutableArray alloc] initWithCapacity:animateNames.count];
        for (NSString * animateName in animateNames) {
            UIImage * animateImage = [UIImage imageNamed:animateName];
            [animationImages addObject:animateImage];
        }
        self.voicImageView.animationImages = animationImages;
        self.voicImageView.animationDuration = 1.0;
        
        
        
        self.leftImageView.hidden = YES;
        self.rightImageView.hidden = YES;
        self.voicImageView.hidden = YES;
        
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(stopPlayVoiceNotification) name:@"stopPlayVoiceNotification" object:nil];

        
    }
    return self;
}

- (void)stopPlayVoiceNotification{
    [self removeStreamerObserver];
    [self.streamer pause];
    self.streamer = nil;
}

- (void)playSound{
    if (!self.dynamicModel.soundAndImageConentModel.SoundUrl.length){
        [MBProgressHUD showMessage:@"当前音频文件为空" finishBlock:nil];
        return;
    }
    
    
    if (self.dynamicModel.isPlaying){
        self.dynamicModel.isPlaying = NO;
        if (self.playMedioBlock){
            self.playMedioBlock(self.dynamicModel);
        }
        [self.streamer pause];
        
    }else{
        self.dynamicModel.isPlaying = YES;
        if (self.playMedioBlock){
            self.playMedioBlock(self.dynamicModel);
        }
        [self createPlayer];
 
    }
}





- (void)clickImageAtIndex:(NSUInteger)index{
    UIView *fromView = nil;
    NSMutableArray *items = [NSMutableArray new];
//    NSArray *pics =_picArr;
    
//    for (NSUInteger i = 0, max = pics.count; i < max; i++) {
        UIView *imgView = self.showImageView;
        YYPhotoGroupItem *item = [YYPhotoGroupItem new];
        item.thumbView = imgView;
        item.largeImageURL = [NSURL URLWithString:_dynamicModel.soundAndImageConentModel.pics[0]];
        item.largeImageSize = CGSizeMake(imgView.width, imgView.height);
        [items addObject:item];
//        if (i == index) {
            fromView = imgView;
//        }
//    }
    
    YYPhotoGroupView *v = [[YYPhotoGroupView alloc] initWithGroupItems:items];
    [v presentFromImageView:fromView toContainer:WINDOW animated:YES completion:nil];
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    if (context == kStatusKVOKey) {
        [self performSelector:@selector(updateStatus)
                     onThread:[NSThread mainThread]
                   withObject:nil
                waitUntilDone:NO];
    } else if (context == kDurationKVOKey) {
        //        [self performSelector:@selector(updateSliderValue:)
        //                     onThread:[NSThread mainThread]
        //                   withObject:nil
        //                waitUntilDone:NO];
    } else if (context == kBufferingRatioKVOKey) {
        //        [self performSelector:@selector(updateBufferingStatus)
        //                     onThread:[NSThread mainThread]
        //                   withObject:nil
        //                waitUntilDone:NO];
    } else {
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}


- (void)updateStatus {
    //    self.musicIsPlaying = NO;
    //    _musicIndicator.state = NAKPlaybackIndicatorViewStateStopped;
    switch ([_streamer status]) {
        case DOUAudioStreamerPlaying:
            break;
            
        case DOUAudioStreamerPaused:
            break;
            
        case DOUAudioStreamerIdle:
            break;
            
        case DOUAudioStreamerFinished:
            [self.voicImageView stopAnimating];
            break;
            
        case DOUAudioStreamerBuffering:
            break;
            
        case DOUAudioStreamerError:
            break;
    }
}



- (void)createPlayer{
    
    
    Track *track = [[Track alloc] init];
    track.audioFileURL = [NSURL URLWithString:self.dynamicModel.soundAndImageConentModel.SoundUrl];
    @try {
        [self removeStreamerObserver];
    } @catch(id anException){
    }
    
    
    _streamer = nil;
    _streamer = [DOUAudioStreamer streamerWithAudioFile:track];
    
    [self addStreamerObserver];
    [self.streamer play];
}

- (void)removeStreamerObserver {
    [_streamer removeObserver:self forKeyPath:@"status"];
    [_streamer removeObserver:self forKeyPath:@"duration"];
    [_streamer removeObserver:self forKeyPath:@"bufferingRatio"];
}

- (void)addStreamerObserver {
    [_streamer addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:kStatusKVOKey];
    [_streamer addObserver:self forKeyPath:@"duration" options:NSKeyValueObservingOptionNew context:kDurationKVOKey];
    [_streamer addObserver:self forKeyPath:@"bufferingRatio" options:NSKeyValueObservingOptionNew context:kBufferingRatioKVOKey];
}


@end
